package cn.edu.nuc.creditSystem.controller.common;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;

import cn.edu.nuc.creditSystem.bean.user.User;
import cn.edu.nuc.creditSystem.service.user.service.MenuService;
import cn.edu.nuc.creditSystem.service.user.service.UserService;

@Controller
public class LoginController{
	@Autowired
	private UserService us;
	@Autowired
	private MenuService ms;
	@RequestMapping("/")
	private String login(){
		return "redirect:/userlogin";
	}
	@RequestMapping("/userlogin")
	private String Userlogin(){
		return "/login";
	}
	@RequestMapping(value="/register",method=RequestMethod.GET)
	private String UserRegister(){
		return "/register";
	}
	@ResponseBody
	@RequestMapping(value="/register",method=RequestMethod.POST)
	private String UserRegister(User user){
		Gson g=new Gson();
		return g.toJson(us.insert(user));
	}
	@ResponseBody
	@RequestMapping(value="/exitsUsername",method=RequestMethod.POST)
	private Boolean ExitsUsername(User user){
		return us.ExitsUsername(user);
	}
	@RequestMapping(value="/checkLogin",method=RequestMethod.POST)
	private String checkLogin(User user,String code,HttpSession session,Model model){
		String randomCode=(String) session.getAttribute("RANDOMCODE");
		if(!"".equals(randomCode) && randomCode.equalsIgnoreCase(code)){
			User u=us.checkUsernameAndPassword(user);
			if(u!=null){
				session.setAttribute("user", u);
				return "redirect:/cs/mySystem";
			}else{
				model.addAttribute("msg","用户名/密码错误！");
				return "forward:/userlogin";
			}
		}else{
			model.addAttribute("username",user.getUsername());
			model.addAttribute("password",user.getPassword());
			model.addAttribute("msg","验证码输入错误！");
			return "forward:/userlogin";
		}
	}
	@RequestMapping("/cs/mySystem")
	private String mySystem(Model model,HttpSession session){
		User user = (User)session.getAttribute("user");
		model.addAttribute("menu",ms.queryMenuByRoleId(user.getRoleId()));
		return "/mySystem";
	}
}
